<?php
namespace app\api\controller\user;

use app\api\controller\Base;
use app\api\controller\mytool\Wechat;
use app\api\controller\Pub;
use app\common\model\company\Company;
use app\common\model\company\Contract;
use app\common\model\company\CompanyTouch as CompanyTouchmodel;
use app\common\model\company\Score as Scoremodel;;
use app\common\model\customer\Customer;
use app\common\model\orderdata\Goods;
use app\common\model\orderhawa\HawaList;
use app\common\model\power\Rolepower;
use app\common\model\power\Rolepowerlnk;
use app\common\model\user\User as UserModel;
use think\facade\Env;
use think\File;

class Hawabuss extends Base
{

    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(201003);
    }

    /**
     * 获取企业信息
     * @return [type] [description]
     */
    public function getcompanyinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数');
        }
        $company = Company::user_getinfo($id);
        if ($company->guard_state) {
            //不许允许看保护的信息
            if (!CUSTOMER_BIND_SHOW_INFO) {
                return moerr('该客户处于保护期,无法查看','','goback');
            }
            //保护期客户将隐藏客户的联系方式\其他电话\负责人电话\负责人姓名\备注\图片备注\
            $company['Tel']      = substr($company['Tel'], 0, 2) . '***' . substr($company['Tel'], -3);
            $company['UserName'] = '该客户处于保护期,无法查看';
            $company['UserTel']  = substr($company['UserTel'], 0, 2) . '***' . substr($company['UserTel'], -3);
            $company['Note']     = '该客户处于保护期,无法查看';
            $company['Img']      = '';
        }
        //为空则给企业返回修改信息
        if (empty($company['UserTel'])) {
            $company['UserTel'] = $company['Tel'];
        }
        //客户所属区域控制
        $company['input_street_area'] =  get_config_value('input_street_area');
        return myok($company);

    }

    /**
     * 获取企业信息
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        
        $data = Company::user_getinfo($id);
        if (empty($data)) {
            return myerr('没有找到此单位');
        }
        $data['guard_state'] = $data->guard_state;
        if(Rolepower::ispower(204007)){
            $role = 'mana';
        }else{
            $role = 'buss';
        }

         //保护期 守卫
        if ($data->guard_state && $data->BussinessId !== Pub::userid()&&$role=='buss') {
            //保护期客户将隐藏客户的联系方式\其他电话\负责人电话\负责人姓名\备注\图片备注\
            $data['Tel']      = substr($data['Tel'], 0, 2) . '***' . substr($data['Tel'], -3);
            $data['UserName'] = '该客户处于保护期,无法查看';
            $data['UserTel']  = substr($data['UserTel'], 0, 2) . '***' . substr($data['UserTel'], -3);
            $rdata['companyinfo'] = $data;
        }else{
            $rdata['companyinfo'] = $data;
            $sdata['Type']         = 'contract';
            $sdata['where']        = [['CompanyId', $id]];
            
            $rdata['contractlist'] = Contract::usergetlist($sdata, $role, false);
            $sdata['Type']         = 'hawa';
            $sdata['where']        = [['CompanyId', $id]];
            $sdata['order']        = 'UpTime desc';
            $sdata['limit']        = '10';
            $rdata['hawaorder']    = HawaList::usergetlist($sdata, $role, false);
            $rdata['UserId']       = Pub::userid();
            $rdata['userinfo']     = UserModel::getinfo('', $data['UserId'])->visible(['Name','Iphone'])->toArray();
            $rdata['StateText']    = Company::getStatusText();
            $rdata['power']        = Rolepowerlnk::getpowerlnk('company');
            //排查清单列表
            $sdata['order']        = 'TouchTime desc';
            $rdata['touchelist']   = CompanyTouchmodel::usergetlist($sdata, $role, false);
            $rdata['company_scores_list']   = Scoremodel::usergetlist($sdata, $role, false);//自查清单
        }
        if(!empty($data['BussinessId'])){
            $rdata['buss'] = UserModel::getinfo('', $data['BussinessId'])->visible(['Name','Iphone'])->toArray();
        }
        $rdata['role'] = $role;
        return myok($rdata);
    }

    /**
     * 获取企业绑定二维码连接
     * @return [type] [description]
     */
    public function getbindurl()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $data = Company::user_getinfo($id);
        if (empty($data)) {
            return myerr('没有找到此单位');
        }
        $rdata['companyinfo'] = $data;
        if (empty($data['UserId'])) {
            $rdata = Wechat::qrcode('bind_hawa_' . SITEPERFIX . '_' . $id);
        }
        return myok($rdata);
    }

    public function getgoodlist()
    {
        $goodlist = Goods::getlist();
        return myok($goodlist);
    }

    /**
     * 修改/完善企业信息
     * 产废人信息也再次完善
     * @return [type] [description]
     */
    public function quickcreatecompanyinfo()
    {
        $data = input('post.');
        //创建一个企业信息
        $data['isplanform'] = 1;
        $result             = $this->validate($data, 'app\common\validate\company\CompanyValidate.companycreate');
        if (true !== $result) {
            return myerr($result);
        }
        $sb = Company::where('Name', $data['name'])->where('Tel', $data['tel'])->find();
        if (!empty($sb)) {
            return myerr('repeat', $sb['CompanyId']);
        }
        $company = Company::user_create($data, 'buss');
        return myok($company);
    }

    /**
     * 修改/完善企业信息
     * 产废人信息也再次完善
     * @return [type] [description]
     */
    public function recompanyinfo()
    {
        $data = input('post.');
        $id   = input('id');
        if (!empty($id)) {
            $company = Company::user_getinfo($id);
        } else {
            $company = [];
        }
        //为空则给企业返回修改信息
        if (empty($data)) {
            return myok($company);
        }

        if (empty($company)) {
            //创建一个企业信息
            $result = $this->validate($data, 'app\common\validate\company\CompanyValidate.companycreate');
            if (true !== $result) {
                return myerr($result);
            }
            $company = Company::user_create($data, 'buss');
            if (empty($data['username'])) {
                return myok($company);
            } else {
                return myok('环保专员信息已完善');
            }
        } else {
            if (!empty($company['UserId']) && !Rolepower::ispower(204015)) {
                return myerr('此产废单位已绑定管理员无法代替修改');
            }
            if ($company['BussinessId'] !== Pub::userid() && !Rolepower::ispower(204015)) {
                return myerr('您对此产废单位没有修改权限');
            }
            //修改企业信息
            $sb = Company::user_reinfo($data, 'buss');
            if (empty($data['username'])) {
                return myok('企业信息已修改');
            } else {
                return myok('环保专员信息已修改');
            }
        }
    }

    /**
     * 获取订单列表
     * @return [type] [description]
     */
    function list() {
        $data            = input('post.');
        $data['where'][] = ['BussinessId', Pub::userid()];
        $data['order']   = 'CreateTime desc';
        $data            = init_where($data);
        $list            = Company::usergetlist($data, 'buss');
        foreach ($list['list'] as $key => $value) {
            if ($value['IsPlanform'] == '1') {
                $list['list'][$key]['IsPlanform'] = '暂未接入';
            } else {
                $list['list'][$key]['IsPlanform'] = '已接入';
            }
            if (!empty($value['UserId'])) {
                $list['list'][$key]['Bind'] = '已绑定';
            } else {
                $list['list'][$key]['Bind'] = '未绑定';
            }
        }

        $list['tr']['title'] = ['单位名称', '地址', '状态', '查看信息', '绑定状态', '登记时间'];
        $list['tr']['key']   = ['Name', 'Address', 'State', 'CompanyId', 'Bind', 'CreateTime'];
        return myok($list);
    }


    /**
     * 生成客户单位信息
     * @return [type] [返回企业id]
     */
    public function create_customer()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr();
        }
        $sb = Company::get($id);
        if (empty($sb)) {
            return myerr();
        }
        $customer = Customer::where('CompanyId',$id)->find();
        if (!empty($customer)) {
            return myerr('此产废单位已经绑定客户档案');
        }
        //自动录入
        $data['Name']          = $sb->Name;
        $data['Address']       = $sb->Address;
        $data['lon']           = $sb->Lon;
        $data['lat']           = $sb->Lat;
        $data['Tel']           = $sb->Tel;
        $data['OtherTel']      = '';
        $data['LicenseNumber'] = $sb->LicenseNumber;
        $data['UserName']      = $sb->UserName;
        $data['UserTel']       = $sb->UserTel;
        $data['Type']          = '';
        $data['Scale']         = '';
        $data['Note']          = '产废单位信息，生成客户档案';
        $data['Img']           = $sb->Img;
        $data['CompanyId']     = $id;
        $customerid            = Customer::user_create($data);
        return myok($customerid);
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = empty(input('type')) ? 'other' : input('type');
        if (!$type == 'company' || !$type == 'user' || !$type == 'order') {
            $type = 'other';
        }
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\hawa\\' . $type . '\\';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
                if ($info) {
//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/hawa/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
